<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <a
          href="javascript:;"
          :class="{ active: !filterInfo.brandsId }"
          @click="filterInfo.brandsId = undefined"
          >全部</a
        >
        <a
          href="javascript:;"
          :class="{ active: filterInfo.brandsId === i.id }"
          @click="filterInfo.brandsId = i.id"
          v-for="i in filterInfo.brands"
          :key="i.id"
          >{{ i.name }}</a
        >
      </div>
    </div>
    <div class="item" v-for="i in filterInfo.saleProperties" :key="i.id">
      <div class="head">{{ i.name }}</div>
      <div class="body">
        <a
          href="javascript:;"
          :class="{ active: !i.propertiesId }"
          @click="i.propertiesId = undefined"
          >全部</a
        >
        <a
          href="javascript:;"
          :class="{ active: i.propertiesId === item.name }"
          @click="i.propertiesId = item.name"
          v-for="item in i.properties"
          :key="item.id"
          >{{ item.name }}</a
        >
      </div>
    </div>
  </div>
</template>
<script>
import { categorySubFilter } from '@/api/category'
import { useRoute, onBeforeRouteLeave } from 'vue-router'
import { ref, watch } from 'vue'
export default {
  name: 'SubFilter',
  setup (props, { emit }) {
    const route = useRoute()
    const filterInfo = ref('')
    //  通过watch观察id的变化，id变化调用接口
    const stop = watch(
      () => route.params.id,
      () => {
        categorySubFilter(route.params.id).then(res => {
          console.log('筛选数据', res)
          filterInfo.value = res.result
        })
      },
      {
        immediate: true
      }
    )
    // 切换路由时，移除watch
    onBeforeRouteLeave(() => {
      stop()
    })
    // 通知父级当前选择了什么
    watch(
      () => filterInfo.value,
      newVal => {
        // 侦听到数据，通知父级emit
        emit('change', {
          brandId: newVal.brandsId,
          attrs: newVal.saleProperties.map(item => {
            return { groupName: item.name, propertyName: item.propertiesId }
          })
        })
      },
      { deep: true }
    )
    return { filterInfo }
  }
}
</script>
<style scoped lang="less">
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
